﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Web;

namespace GateKeeper
{
    public class AccessDenied
    {
        /// <summary>
        /// Displays the Access Denied message to the request
        /// and terminates the request with a 403 - Access Denied
        /// </summary>
        public static void Display(HttpContext current, Violation violation)
        {
            GateKeeperModule.log.Debug("Entering AccessDenied");
            GateKeeperModule.log.DebugFormat("Request denied [{0}]", violation.ToString());

            try
            {
                if (GateKeeperModule.config.DisplayContactForm 
                            && !string.IsNullOrEmpty(GateKeeperModule.config.ContactFormUrl))
                {
                    //current.Response.Redirect(string.Format("{0}/{1}", current.Request.ApplicationPath, GateKeeperModule.config.ContactFormUrl), false);
                    current.Response.StatusCode = 403;
                    current.Server.Transfer(string.Format("{0}/{1}", current.Request.ApplicationPath, GateKeeperModule.config.ContactFormUrl));
                }
                else
                {
                    current.Response.Write(GateKeeperModule.config.AccessDeniedMessage);
                    current.Response.StatusCode = 403;
                }
            }
            finally
            {
                onDenyAccess(current);
                GateKeeperModule.log.Debug("Leaving AccessDenied");
                current.Response.StatusDescription = "Access is denied";
                current.Response.End();
            }
        }

        #region events
        public static event EventHandler<EventArgs> DenyAccess;
        private static void onDenyAccess(HttpContext current)
        {
            if (DenyAccess != null)
            {
                GateKeeperModule.log.Debug("Executing DenyAccess eventHandler");
                DenyAccess(current, new EventArgs()); 
            }
        }
        #endregion //events
    }
}
